package com.ok.common.utils

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

/**
 * 定时任务
 */
class Timer(
    private var initialDelayMs: Long = 0L, // 首次执行的延迟时间
    private var intervalMs: Long = 0L, //定时间隔时间
    startImmediately: Boolean = false, //是否直接启动
    private val callback: () -> Unit
) {

    private var job: Job? = null

    init {
        if (startImmediately) {
            start()
        }
    }

    fun start(initialDelayMs: Long = this.initialDelayMs, intervalMs: Long = this.intervalMs) {
        if (intervalMs <= 0L) {
            return
        }
        this.intervalMs = intervalMs
        if (job?.isActive != true) {
            job = CoroutineScope(Dispatchers.Main).launch {
                // 首次延迟执行
                if (initialDelayMs > 0L) {
                    delay(initialDelayMs)
                    callback.invoke()
                }
                while (isActive) {
                    delay(intervalMs)
                    callback.invoke()
                }
            }
        } else {
            stop()
            start()
        }
    }

    fun stop() {
        job?.cancel()
    }

}
